import {Component, ViewChild} from '@angular/core';
import {
  AlertController,
  Content,
  InfiniteScroll,
  IonicPage,
  ModalController,
  NavController,
  PopoverController
} from 'ionic-angular';
import {DialogProvider} from "@providers/dialog";
import {HttpProvider} from "@providers/http";
import {StorageProvider} from "@providers/storage";
import {PagingConfig} from "@providers/paging";
import {WorkerProvider} from "@providers/interface/worker";
import {Util} from "@providers/util";
import {NativeProvider} from "@providers/natives/native";
import {env} from "@env/environment";

@IonicPage()
@Component({
  selector: 'page-worker-look',
  templateUrl: 'worker-look.html',
})
export class WorkerLookPage {
  @ViewChild('tel') tel: any;
  @ViewChild(Content) content: Content;
  userInfo: any;
  datas: any[] = [];
  datasConfig: PagingConfig = new PagingConfig();
  isScrollDown = false;//判断页面是否是向下滑动
  azlist: any = [];//辅助人员
  index: any;
  query_field: any = "";//查询条件
  CDKG: any;
  datasNum = 0;//单据数量
  isApp;
  dev: boolean;

  isShowDate: number = 0;//日期选择器展示参数

  YYSJ:any={
    from:'',
    to:''
  };//查询条件：预约时间

  constructor(private alertCtrl: AlertController,
              private dialog: DialogProvider,
              private http: HttpProvider,
              private navCtrl: NavController,
              private storage: StorageProvider,
              private worker: WorkerProvider,
              private native: NativeProvider,
              private modalCtrl: ModalController,
              private popoverCtrl: PopoverController,) {
    this.userInfo = this.storage.read("userInfo");
    this.azlist = this.storage.read("azlist") ? this.storage.read("azlist") : [];
    this.isApp = this.native.isCordova;
    this.dev = env.mode == "prod";
  }

  ionViewWillEnter() {
    this.userInfo = this.storage.read("userInfo");
    this.datas = [];
    this.CDKG = "";
    this.CDKG = this.userInfo["CDKG"];
    this.datasConfig = new PagingConfig();
    if (this.userInfo.SFZX != '0') {
      this.content.getScrollElement().style["margin-top"] = '95px';
      this.getData(data => {
        this.datas = data;
      }, this.datasConfig);
      this.getOrdersNum();
    } else {
      this.content.getScrollElement().style["margin-top"] = '45px';
    }
  }

  push(page: string, data: any) {
    data["SP"] = data.CSM_SORDERITEM[0];
    this.navCtrl.push(page, data);
  }

  /**
   * 选择辅助人员
   */
  selectAZRY() {
    let modal = this.modalCtrl.create('WorkerLookDecorationPage', this.azlist);
    modal.onDidDismiss((da) => {
      if (da) {
        this.azlist = da;
        this.storage.write("azlist", this.azlist);
      }
    });
    modal.present();
  }

  /**
   * 滑动时触发
   */
  scrollContent() {
    this.isScrollDown = this.content.directionY == "down";
  }

  /**
   * 刷新数据
   */
  refresh(refresher?: any) {
    this.getOrdersNum();
    this.datasConfig = new PagingConfig();
    this.getData(data => {
      this.datas = data;
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
    }, this.datasConfig, error => {
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
    });
  }


  activemodel(date: any) {
    let types = [];
    JSON.parse(date.DHLB).forEach(value => {
      types.push({
        text: value,
        handler: () => {
          this.native.call(value);
        }
      })
    });
    this.dialog.showActionSheet(types, '请选择客户电话！');
  }

  getMoreDatas(infiniteScroll: InfiniteScroll) {
    this.getData((value) => {
      this.datas.push.apply(this.datas, value);
      infiniteScroll.complete();
    }, this.datasConfig);
  }

  /**
   * 获取数据
   * @param pagingConfig 分页
   * @param fn 方法
   * @param errorFun 方法
   * @param YYSJ 按照预约时间查询
   */
  private getData(fn: (value) => void, pagingConfig, errorFun?: (error) => void,YYSJ?:any) {
    if (this.userInfo.SFZX != '0') {
      this.worker.selectSOrder(
        {"FW": "FW", "WORKER": this.userInfo.PARTYID, 'query': this.query_field, YYSJ: YYSJ},
        pagingConfig
      ).then(data => {
        data = data || [];
        for (let i = 0; i < data.length; i++) {
          let v = data[i];
          v["isshangmeng"] = false; //没上门 可以去上门装车
          v.CSM_SORDERITEM = v.CSM_SORDERITEM || [];
          for (let j = 0; j < v.CSM_SORDERITEM.length; j++) {
            let va = v.CSM_SORDERITEM[j];
            if (va.JDBJ == 1) {
              v["isshangmeng"] = true;
              v.isZC = true;
            }
            if (this.userInfo.GSCS == 5) {
              if (va.PICKING == 'false') {
                v.PICKING = false;
                v.isZC = false;
              } else {
                v.PICKING = true;
              }
            }

            if (v.GUARANTEE == 1) {
              v.GUARANTEE = '保内';
            } else if (v.GUARANTEE == 2) {
              v.GUARANTEE = '保外';
            } else if (v.GUARANTEE == 3) {
              v.GUARANTEE = '延保';
            } else {
              v.GUARANTEE = '无';
            }

          }

          let d: Date = new Date(v.THRUTIME);
          if (!isNaN(v.THRUTIME)) {
            v.THRUTIME = Util.dateFormat(d, "yyyy-MM-dd")
          }
        }
        fn(data);
      }).catch(e => {
        if (errorFun) {
          errorFun(e);
        }
      });
    }
  }


  //上门
  dispaly(data: any, i: number) {
    this.dialog.showConfirm(() => {
      this.dialog.showLoading();
      this.http.post("/Inbound/invoke.do", {
        interfaceId: 'csm.som.ext.cssOrder.load',
        data: JSON.stringify({'id': data.ID})
      }).subscribe(message => {
        data.isshangmeng = true;
        this.dialog.hideLoading();
      }, error => {
        this.dialog.hideLoading();
        this.dialog.showAlert(error);
        return;
      })
    }, "是否上门")
  }

  access(data: any, i: number) {
    this.navCtrl.push("WorkerMaterielStorePage", data);
  }

  pick(data: any, i: number) {
    this.worker.pick(this.datas[i].ID).then(data => {
      if (data.ISPICKING == 'true') {
        this.datas[i].PICKING = true;
      }
    }).catch(e => {
      this.dialog.showAlert("拣货出错");
    });
  }

  tuidan(da: any, i: number) {
    let prompt = this.alertCtrl.create({
      title: '撤单原因',
      message: "撤单原因为必填项，请说明为什么要撤这个单子！",
      inputs: [
        {
          name: 'cdbz',
          placeholder: '请填写撤单原因！'
        }
      ],
      buttons: [
        {
          text: '取消',
          handler: data => {
          }
        },
        {
          text: '确定',
          handler: val => {
            if (Util.isNull(val.cdbz.trim())) {
              this.dialog.showToast("撤单原因不允许为空！");
              return false;
            }
            this.dialog.showLoading();
            this.http.post("/Inbound/invoke.do", {
              interfaceId: 'csm.som.ext.cssOrder.recall',
              data: JSON.stringify({"canceler": this.userInfo.PARTYID, 'id': da.ID, "cdbz": val.cdbz})
            }).subscribe(message => {
              this.dialog.hideLoading();
              // this.dialog.showAlert("拒单成功！");
              this.datas.splice(i, 1);
            }, error => {
              this.dialog.hideLoading();
              this.dialog.showAlert(error);
            });
          }
        }
      ]
    });
    prompt.present();
  }

  update(data: any, i: number) {//修改工单
      this.navCtrl.push("WorkerLookOrderModifyPage", data);
    // this.navCtrl.push("WorkerLookDelayreasonPage", data);
    // let prompt = this.popCtrl.create("DelayreasonPage");
    // prompt.onDidDismiss((data)=>{
    //   if(Util.isNull(data)){
    //     return;
    //   }
    //   this.dialog.showLoading();
    //             this.http.post("/Inbound/invoke.do", {
    //               interfaceId: 'csm.som.cssOrder.makeSorderYCFW',
    //               data: JSON.stringify({"CZYMC": this.userInfo.username, "YYSJ": data.YYSJ,
    //               "GD01":data.ID,"BZ":data.reason})
    //             }).subscribe(message => {
    //               this.dialog.hideLoading();
    //               this.datas.splice(i, 1);
    //             }, error => {
    //               this.dialog.hideLoading();
    //               this.dialog.showAlert(error);
    //             });
    // })
    //  prompt.present();
  }

  /**
   * 装车
   * @param data
   * @param i
   */
  submit(data: any, i: number) {
    this.dialog.showConfirm(() => {
      this.dialog.showLoading();
      this.http.post("/Inbound/invoke.do", {
        interfaceId: 'csm.som.ext.cssOrder.load',
        data: JSON.stringify({"ITEM": data.CSM_SORDERITEM})
      }).subscribe(message => {
        this.datas[i].isZC = true;
        this.dialog.hideLoading();
      }, error => {
        this.dialog.hideLoading();
        this.dialog.showAlert("装车失败！" + error);
        return;
      });
    }, "是否确定装车？");
  }

  /**
   * 完工按钮点击事件
   * @param page
   * @param date
   * @param i
   */
  openpage(page: string, date: any, i: number) {
    date.work = this.azlist;
    let modal = this.modalCtrl.create(page, date);
    modal.onDidDismiss((bor) => {
      if (bor) {
        this.datas.splice(i, 1);
      }

    });
    modal.present();
    //  this.navCtrl.push(page,date);
  }

  /**
   * 开工
   */
  switchIsWorking() {
    this.worker.switchIsWorking(this.userInfo["PARTYID"], '10').then(v => {
      this.userInfo.SFZX = v.data["SFZX"];
      this.storage.write('userInfo', this.userInfo);
    }).then(() => {
      this.content.getScrollElement().style["margin-top"] = '95px';
      this.datasConfig = new PagingConfig();
      this.getData(data => {
        this.datas = data;
      }, this.datasConfig);
      this.getOrdersNum();
    }).catch(e => {
    })
  }

//获取单据数量
  getOrdersNum() {
    if (this.userInfo.SFZX != '0') {
      this.worker.getOrdersNum({
        "FW": "FW",
        "WORKER": this.userInfo.PARTYID
      }).then(v => {
        this.datasNum = v.data.SL;
      }).catch(e => {
        this.dialog.showAlert('请检查网络！' + e);
      });
    }
  }

  /**
   * 挂单
   * @param data
   * @param i
   */
  posters(data: any, i: number) {
    let prompt = this.popoverCtrl.create('PostersPage', data, {cssClass: 'sum'});
    prompt.onDidDismiss((data) => {
      if (data) {
        this.refresh();
      }
    });
    prompt.present();
  }

  postersEnd(data: any, i: number) {
    this.worker.makeGuaDanDown({ID: data.ID}).then((message) => {
      this.refresh();
    }).catch((error) => {

    })
  }

  /**
   * 转到地图显示工单页面
   */
  mapDisplatOrder() {
    this.navCtrl.push('MapDisplayOrderPage', this.datas);
  }

  viewQrCode(content) {
    this.native.getQrCode(content).then(res => {
      let img = document.createElement('img');
      img.src = res;
      this.native.viewImg(img);
    })
  }

  showDate(item) {
    this.isShowDate = item == 1 ? 0 : 1;
  }

  change(v) {
    if(v.type==1){
      this.YYSJ.from=v.date;
      this.YYSJ.to=v.date;
    }else if(v.type ==3){
      let date=Util.stringToDate(v.date);
      this.YYSJ.from=Util.dateToString(date);
      date.setMonth(date.getMonth()+1);
      date.setDate(date.getDate()-1);
      this.YYSJ.to=Util.dateToString(date);
    }else if(v.type ==4){
      let date=Util.stringToDate(v.date+"-01-01");
      this.YYSJ.from=Util.dateToString(date);
      date.setFullYear(date.getFullYear()+1);
      date.setDate(date.getDate()-1);
      this.YYSJ.to=Util.dateToString(date);
    }else{
      this.YYSJ.from = v.date[0];
      this.YYSJ.to = v.date[1];
    }
  }

  searchOrderByTime() {
    this.isShowDate = 0;
    this.datasConfig = new PagingConfig();
    this.getData(data => {
      this.datas = data;
    }, this.datasConfig,null,this.YYSJ);
  }

  exit() {
    this.isShowDate = 0;
  }

}
